package com.zzxx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzxx.mapper.UserMapper;
import com.zzxx.pojo.UserInfo;
import com.zzxx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	@Override
	public PageInfo<UserInfo> findAll(Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum,pageSize);
		List<UserInfo> list = userMapper.findAll();
		PageInfo<UserInfo> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserInfo userInfo = userMapper.findByUsername(username);
		if (Objects.isNull(userInfo)) { // 用户不存在
			throw new AuthenticationException("账号不存在"){};
		}
		// 设置固定角色 - 用来做授权
		List<GrantedAuthority> list = new ArrayList<>();
		list.add(new SimpleGrantedAuthority("ROLE_USER"));

		User user = new User(userInfo.getUsername(), userInfo.getPassword(), list);
		return user;
	}
}
